package controller;

import moder.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login.do")
public class LoginController extends HttpServlet {
    service.UserService us = new service.impl.UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String upassword = request.getParameter("upassword");

        User user = us.getUserByLoginId(username, upassword);
        if(user!=null) { //存在该用户
            if(request.getParameter("ck")!=null){
                //记录密码
                Cookie cook_name = new Cookie("username",username);
                Cookie cook_pwd = new Cookie("upassword",upassword);
                //设置cookie的携带路径
                cook_name.setPath(request.getContextPath());
                cook_pwd.setPath(request.getContextPath());
                cook_name.setMaxAge(60*60*24*7);
                cook_pwd.setMaxAge(60*60*24*7);
                response.addCookie(cook_name);
                response.addCookie(cook_pwd);
            }
            request.getSession().setAttribute("user", user);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            }else {//当直接访问该controller的时候并没有user所以要进登陆界面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}
